<template>
  <BasicModal @register="registerModal" title="JS增强" :width="800" :bodyStyle="{ height: '360px' }">
    <template #footer>
      <a-space>
        <a-button @click="onCancel">关闭</a-button>
        <a-button type="primary" @click="onSubmit">确定</a-button>
      </a-space>
      <a-space style="float: left">
        <a-button v-if="showHistory" @click="onShowHistory">查看历史版本</a-button>
        <a-button v-if="aiTestMode" @click="onGenTestData">生成测试数据</a-button>
      </a-space>
    </template>

    <template #default>
      <a-tabs v-model:activeKey="enhanceType" @change="onChangeType">
        <a-tab-pane tab="form" key="form" forceRender>
          <JCodeEditor
            v-if="!reloading"
            ref="formEditorRef"
            v-model:value="enhanceValues.form"
            language="javascript"
            :fullScreen="true"
            :lineNumbers="false"
            height="240px"
            :language-change="false"
            @change="onCodeChange"
          />
        </a-tab-pane>
        <a-tab-pane tab="list" key="list" forceRender>
          <JCodeEditor
            v-if="!reloading"
            ref="listEditorRef"
            v-model:value="enhanceValues.list"
            language="javascript"
            :fullScreen="true"
            :lineNumbers="false"
            height="240px"
            :language-change="false"
            @change="onCodeChange"
        /></a-tab-pane>
      </a-tabs>
      <EnhanceJsHistory @register="registerEnhanceJsHistory" />
    </template>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { JCodeEditor } from '/@/components/Form';
  import { useOnlineTest } from '../../use/useOnlineTest';
  import { useEnhanceStore } from './EnhanceJsHistory.vue';
  import EnhanceJsHistory from './EnhanceJsHistory.vue';
  import { getEnhanceJsByCode, saveEnhanceJs } from './enhance.api';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'EnhanceJs',
    components: { BasicModal, JCodeEditor, EnhanceJsHistory },
    emits: ['register'],
    setup() {
      const { createMessage: $message } = useMessage();
      const enhanceStore = useEnhanceStore();
      const formEditorRef = ref();
      const listEditorRef = ref();
      const models = reactive({ form: {}, list: {} });
      const enhanceType = ref('list');
      const code = ref('');
      const showHistory = ref(false);
      const codeChange = ref(false);
      const tableName = ref('');
      const enhanceValues = reactive({ form: '', list: '' });
      const getFlag = { form: false, list: false };
      const reloading = ref(false);
      const [registerModal, { closeModal }] = useModalInner(async (data) => {
        show(data.row);
      });
      const [registerEnhanceJsHistory, enhanceJsHistory] = useModal();
      const { aiTestMode, genEnhanceJsData } = useOnlineTest();
      function show(row) {
        code.value = row.id;
        codeChange.value = false;
        tableName.value = row.tableName;
        let enhances = enhanceStore.getEnhanceJs(code.value);
        if ((enhances == null ? void 0 : enhances.length) > 0) {
          enhanceType.value = enhances[enhances.length - 1].type;
          showHistory.value = true;
        } else {
          showHistory.value = false;
        }
        getFlag.form = false;
        getFlag.list = false;
        if (!enhanceType.value) {
          onChangeType('form');
        } else {
          onChangeType(enhanceType.value);
        }
        reloading.value = true;
        setTimeout(() => (reloading.value = false), 150);
      }
      async function onSubmit() {
        await Promise.all([saveEnhanceJsByType('form'), saveEnhanceJsByType('list')]);
        closeModal();
        $message.success('保存成功');
      }
      async function saveEnhanceJsByType(type) {
        let model = models[type];
        let params = {
          cgJs: enhanceValues[type],
          cgJsType: type,
        };
        if (!getFlag[type] || model.cgJs === params.cgJs) {
          return;
        }
        let isUpdate = !!model.id;
        if (isUpdate) {
          params = Object.assign({}, model, params);
        }
        await saveEnhanceJs(code.value, params, isUpdate);
        enhanceStore.addEnhanceJs({
          code: code.value,
          str: params.cgJs,
          type: params.cgJsType,
          date: new Date().getTime(),
        });
      }
      function onCancel() {
        closeModal();
      }
      async function onChangeType(type) {
        enhanceType.value = type;
        try {
          if (!getFlag[type]) {
            let result = await getEnhanceJsByCode(code.value, type);
            Object.assign(models[type], { id: null }, result);
            enhanceValues[type] = models[type].cgJs;
            getFlag[type] = true;
          }
        } catch (e) {
          console.error(e);
        }
        setTimeout(() => {
          if (type == 'list') {
            listEditorRef.value.refresh();
          } else {
            formEditorRef.value.refresh();
          }
        }, 150);
      }
      function onShowHistory() {
        enhanceJsHistory.openModal(true, {
          code: code.value,
          type: enhanceType.value,
        });
      }
      function onCodeChange(value) {
        if (enhanceValues[enhanceType.value] != value) {
          codeChange.value = true;
          enhanceValues[enhanceType.value] = value;
        }
      }
      function onGenTestData() {
        if (enhanceType.value === 'form') {
          genEnhanceJsData(tableName.value, enhanceType.value, formEditorRef.value);
        } else {
          genEnhanceJsData(tableName.value, enhanceType.value, listEditorRef.value);
        }
      }
      return {
        formEditorRef,
        listEditorRef,
        reloading,
        enhanceValues,
        enhanceType,
        showHistory,
        aiTestMode,
        tableName,
        genEnhanceJsData,
        onGenTestData,
        onChangeType,
        onCodeChange,
        onShowHistory,
        onSubmit,
        onCancel,
        registerModal,
        registerEnhanceJsHistory,
      };
    },
  });
</script>
<style scoped></style>
